#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
# @FileName  :jobs.py
# @Time      :2022/4/25 2:25 PM
# @Author    :Toliong toliong@foxmail.com
"""
from sqlalchemy.orm import Session
from db.models.jobs import Job
from schemas.jobs import JobCreate


def create_new_job(job: JobCreate, db: Session, owner_id: int):
    job_object = Job(**job.dict(), owner_id=owner_id)
    db.add(job_object)
    db.commit()
    db.refresh(job_object)
    return job_object


def retreive_job(job_id: int, db: Session):
    item = db.query(Job).filter(Job.id == job_id).first()
    return item


def list_jobs(db: Session):
    jobs = list(db.query(Job).filter(db.is_active==True))
    return jobs


def update_job_by_id(job_id: int, job: JobCreate, db: Session, owner_id):
    existing_job = db.query(Job).filter(Job.id == job_id)
    if not existing_job.first():
        return 0
    job.__dict__.update(owner_id=owner_id)  #update dictionary with new key value of owner_id
    existing_job.update(job.__dict__)
    db.commit()
    return 1


def delete_job_by_id(job_id: int, db: Session, owner_id):
    existing_job = db.query(Job).filter(Job.id == job_id)
    if not existing_job.first():
        return 0
    existing_job.delete(synchronize_session=False)
    db.commit()
    return 1


if __name__ == "__main__":
    pass
